#!/bin/bash
current_dir=$(cd $(dirname $0); pwd)
# 导入配置文件
# source ${current_dir}/config.cnf

pgbackrest=/usr/bin/pgbackrest
stanza=${bak_stanza_name}
pg_backupdir=/app/backup
who=$(whoami)
# 备份时长间隔
#task_interval="55 02 * * *"
task_interval=$1

# 打印
comm_print_note(){
    local msg=$1
    echo -e "$(date +"%Y-%m-%d %H:%M:%S") \033[32m[Note]\033[0m ${msg} "
}

comm_print_error(){
    local msg=$1
    echo -e "$(date +"%Y-%m-%d %H:%M:%S") \033[31m[Error]\033[0m ${msg}"
}

# 判断是否是主,非主则退出
function is_primary(){
  comm_print_note "判断是否为主实例..."
  if [ $who = "postgres" ];then
    local check_master_or_slave=$(psql -c 'select pg_is_in_recovery();'|grep t|wc -l)
  else
    local check_master_or_slave=$(su - postgres -c "psql -c 'select pg_is_in_recovery();'"|grep t|wc -l)
  fi
  if [ $? -gt 0 ];then
    comm_print_error "请查看PG是否正常启动..."
    exit 1
  fi 
  if [ $check_master_or_slave -eq 1 ];then
    comm_print_note "当前实例不为主实例，无需进行其他操作..."
    exit 1
  else
    comm_print_note "当前实例为主实例..."
  fi
}

# 创建备份目录
function backup_stanza_create(){
  is_primary
  comm_print_note "创建备份目录 stanza_create"
  if [ $who = "postgres" ];then
    ${pgbackrest} --stanza=${stanza} --log-level-console=info stanza-create
    backup_status $?
  else
    su - postgres -c "${pgbackrest} --stanza=${stanza} --log-level-console=info stanza-create"
    backup_status $?
  fi
}

# 备份环境ckeck
function backup_stanza_check(){
  is_primary
  comm_print_note "备份环境检查 check"
  if [ $who = "postgres" ];then
    ${pgbackrest} --stanza=${stanza} --log-level-console=info check
    backup_status $?
  else
    su - postgres -c "${pgbackrest} --stanza=${stanza} --log-level-console=info check"
    backup_status $?
  fi
}

# 全备
function backup_full(){
  is_primary
  comm_print_note "进行全量备份 ..."
  if [ $who = "postgres" ];then
    ${pgbackrest} --stanza=${stanza} --log-level-console=info --type=full backup
    backup_status $?
  else
    su - postgres -c "${pgbackrest} --stanza=${stanza} --log-level-console=info --type=full backup"
    backup_status $?
  fi
}

# 增备
function backup_incr(){
  is_primary
  comm_print_note "进行增量备份 ..."
  if [ $who = "postgres" ];then
      ${pgbackrest} --stanza=${stanza} --log-level-console=info --type=incr backup
      backup_status $?
  else
      su - postgres -c "${pgbackrest} --stanza=${stanza} --log-level-console=info --type=incr backup"
      backup_status $?
  fi
}

# 检查备份状态
function backup_status(){
  bk_status=$1
  # 输出备份结果
  if [ $bk_status -eq 0 ]; then
    comm_print_note "Execute successful"
  else
    comm_print_error "Execute failed!"
  fi
}

function is_not_exists_crontab(){
  #comm_print_note "判断是否已存在 crontab 备份任务..."
  local c_status=$(cat /etc/crontab|grep 'backup_pgbackrest.sh'|wc -l)
  if [ $c_status -eq 0 ];then
    return 0
  else
    return 1
  fi
}

function backup_add_crontab(){
  comm_print_note "执行添加 crontab 备份任务..."
  if is_not_exists_crontab;then
    echo "${task_interval} root /bin/bash ${current_dir}/backup_pgbackrest.sh full >> ${pg_backupdir}/exec_cron_backup.log 2>&1" |sudo tee -a /etc/crontab
  fi
  comm_print_note "已添加 crontab 备份任务."
}

# 删除配置的定时任务
function backup_del_crontab(){
  comm_print_note "执行删除crontab 定时备份任务[/etc/crontab]..."
  if ! is_not_exists_crontab;then
   sudo sed -i '/backup_pgbackrest.sh/d' /etc/crontab
  fi
}

# 使用说明
usage () {
        cat <<EOF
Usage: $0 [OPTIONS]
  create                    创建备份目录与准备环境
  check                     检查备份环境
  full                      执行全备
  incr                      执行增备
  add_crontab               添加备份定时任务，默认备份时间为每日[02:55]
  del_crontab               删除添加的备份定时任务
EOF
exit 1
}

# main 入口
command="${1}"
case "${command}" in
    "create" )
	    backup_stanza_create
    ;;
    "check" )
	    backup_stanza_check
    ;;
    "full" )
	    backup_full
    ;;
    "incr" )
	    backup_incr
    ;;
    "add_crontab" )
	    backup_add_crontab
    ;;
    "del_crontab" )
	    backup_del_crontab
    ;;
    * )
        usage
    ;;
esac